package org.rvk.vms.dal.dao;

import org.rvk.vms.dal.cache.State;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 *  Generic JDBC DAO Implementation.
 *
 * @author Ashish Kumar Sinha <aksinha.mail@gmail.com>
 */
@Service("genericJdbcDao")
@Scope((BeanDefinition.SCOPE_SINGLETON))
public class GenericJdbcDaoImpl extends JdbcDaoSupport implements GenericJdbcDao {

    /**
     * to fetch the state wise volunteers count.
     *
     * @return the state wise volunteers count.
     */
    @Override
    public Map<State, Integer> volunteersCountPerState() {
        String queryVolunteersCountPerState =  "SELECT state, count(id) as count FROM volunteer WHERE isMaster = 1 GROUP BY state ";
        final Map<State, Integer> mapVolunteersCountPerState = new HashMap<>();
        getJdbcTemplate().query(queryVolunteersCountPerState, new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet resultSet) throws SQLException {
                String state = resultSet.getString("state");
                Integer count = resultSet.getInt("count");
                State theState = State.getState(state);
                mapVolunteersCountPerState.put(theState, count);
            }
        });

        return mapVolunteersCountPerState;
    }
}
